﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Drawing;
using System.Data;

namespace HOOMT
{
    class MainFormDBO : SqliteDataBaseOperator
    {
        RMainFormToFormDBO rdbo = new RMainFormToFormDBO();
        public bool AddMainForm(MainForm form)
        {
            // Console.WriteLine(form.GetType());
            try
            {


                this.DeleteMainForm(form);
                //   this.conn = this.GetConnection();
                SQLiteCommand cmd = this.GetCmd();
                cmd.CommandText = "insert into MainForm( id ,projectName,savedate)  "
                   + "values (@id,@projectName,@savedate)";
                cmd.Parameters.Add(new SQLiteParameter("id", form.id));
                cmd.Parameters.Add(new SQLiteParameter("projectName", form.projectName));
                cmd.Parameters.Add(new SQLiteParameter("savedate",
                    System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

                cmd.ExecuteNonQuery();

                rdbo.AddRelations(form);
                //if (form.modelFormList != null)
                //{
                //    foreach (OriginalModelForm omf in form.modelFormList)
                //    {

                //        sqlitecommand cmd1 = this.getcmd();
                //        cmd1.commandtext = "insert into  r_mainform_form(id,mainformid,formid,formtype) values (@id,@mainformid,@formid,@formtype)";
                //        cmd1.parameters.add(new sqliteparameter("id", system.guid.newguid()));
                //        cmd1.parameters.add(new sqliteparameter("mainformid", form.id));
                //        cmd1.parameters.add(new sqliteparameter("formid", omf.id));
                //        cmd1.parameters.add(new sqliteparameter("formtype", omf.gettype().tostring()));
                //        cmd1.executenonquery();
                //    }
                //}

                this.CloseConnection();
                return true;

            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }

        }


        //         public List<OriginalModelForm> GetFormListByMainFormId(String mainFormId, MainForm mainForm)
        //         {
        //             List<OriginalModelForm> list = new List<OriginalModelForm>();
        // 
        //             try
        //             {
        // 
        //                 SQLiteCommand cmd = GetCmd();
        //                 cmd.CommandText = "select * from r_mainform_form where mainformid=@mainformid";
        //                 cmd.Parameters.Add(new SQLiteParameter("mainformid", mainFormId));
        //                 SQLiteDataReader reader = cmd.ExecuteReader();
        //                 while (reader.Read())
        //                 {
        //                     String formId = reader["formId"].ToString();
        //                     String formType = reader["formType"].ToString();
        //                     if ("ObjectModelForm".Equals(this.GetSimpleType(formType)))
        //                     {
        //           //              Console.WriteLine("ObjectModelForm");
        //                         ObjectModelFormDBO dbo = new ObjectModelFormDBO();
        //                         ObjectModelForm form = dbo.GetObjectModelFormById(formId, mainForm);
        //                         list.Add(form);
        //                     }
        //                     else
        //                     {
        //                     }
        //                 }
        //             }
        //             catch (System.Exception ex)
        //             {
        //                 Console.WriteLine(ex.ToString());
        //                 return null;
        //             }
        //             return list;
        //         }

        public bool HasMainForm(String Id)
        {
            SQLiteCommand cmd = this.GetCmd();
            cmd.CommandText = "select * from mainform where id=@id";
            cmd.Parameters.Add(new SQLiteParameter("id", Id));
            SQLiteDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
                return true;
            else
                return false;

        }
        //这个方法有问题，目前暂时解决问题

        public bool DeleteMainForm(MainForm mainForm)
        {
            try
            {
                SQLiteCommand cmd = this.GetCmd();
                cmd.CommandText = "delete from mainform where id =@id";
                cmd.Parameters.Add(new SQLiteParameter("id", mainForm.id));
                cmd.ExecuteNonQuery();
                /*RMainFormToFormDBO rdbo = new RMainFormToFormDBO();*/
                rdbo.DeleteRelations(mainForm);
                return true;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }
        // 
        //         public bool UpdateMainForm(MainForm mainForm)
        //         {
        //             try
        //             {
        //                 RMainFormToFormDBO rdbo = new RMainFormToFormDBO();
        //                 rdbo.DeleteRelations(mainForm);
        //                 SQLiteCommand cmd = this.GetCmd();
        //                 cmd.CommandText = "delete from mainform where id =@id";
        //                 cmd.Parameters.Add(new SQLiteParameter("id", mainForm.id));
        //                 cmd.ExecuteNonQuery();
        //                 this.AddMainForm(mainForm);
        //                 return true;
        //             }
        //             catch (System.Exception ex)
        //             {
        //                 Console.WriteLine(ex.ToString());
        //                 return false;
        //             }
        // 
        // 
        //         }

        public bool SaveMainForm(MainForm mainForm)
        {
            try
            {

                AddMainForm(mainForm);



                return true;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }

        public bool CleanUp()
        {
            try
            {
                SQLiteCommand cmd = this.GetCmd();
                cmd.CommandText = "delete  from MainForm";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from OriginalModelForm";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from OriginalDiagram";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from r_form_diagram";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from r_mainform_form";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from method";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from attribute";
                cmd.ExecuteNonQuery();
                cmd.CommandText = "delete  from OriginalLine";
                cmd.ExecuteNonQuery();


                return true;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
            finally
            {
                this.CloseConnection();
            }
        }

        public bool GetMainFormById(String id, MainForm thisMainForm)
        {
            try
            {
                SQLiteCommand cmd = GetCmd();
                cmd.CommandText = "select * from mainform where id=@id";
                cmd.Parameters.Add(new SQLiteParameter("id", id));

                SQLiteDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    thisMainForm.id = id;
                    thisMainForm.projectName = reader["projectName"].ToString();

                    foreach (OriginalModelForm omf in thisMainForm.modelFormList)
                    {
                        omf.Visible = false;
                    }

                    thisMainForm.modelFormList.Clear();
                    //张帆 注意。解决了load后Form位置偏离的问题
                    OriginalModelForm.locationPoint = new Point(0, 0);
                    thisMainForm.modelFormList.AddRange(rdbo.GetRelations(id, thisMainForm));
                    foreach (OriginalModelForm omf in thisMainForm.modelFormList)
                    {
                        omf.BringToFront();
                        if (omf.Visible)
                            omf.Show();


                        omf.Focus();
                        //            Console.WriteLine(omf.ToString());
                        foreach (OriginalDiagram od in omf.diagramList)
                        {
                            //               Console.WriteLine(od.ToString());
                        }
                    }
                }
                //添加图的子Form的关联
                this.AddSubFormForAllDiagrams(thisMainForm);
                return true;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
            finally
            {
                this.CloseConnection();
            }
        }

        public DataTable GetAllProject()
        {
            DataTable dt = new DataTable();
            try
            {

                SQLiteCommand cmd = GetCmd();
                cmd.CommandText = "SELECT * FROM mainform";

                SQLiteDataReader dr = cmd.ExecuteReader();
                if (dr.HasRows)
                {
                    dt.Load(dr);
                }
                else
                {
                    //throw new NullReferenceException("No Record Available.");
                }



            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());

            }
            finally
            {
                this.CloseConnection();
            }
            return dt;
        }

        //         public List<OriginalModelForm> GetSubFormList(MainForm mainForm)
        //         {
        //             List<OriginalModelForm> subFormList = new List<OriginalModelForm>();
        //             try
        //             {
        //                 SQLiteCommand cmd = this.GetCmd();
        //                 cmd.CommandText = "SELECT * FROM OriginalDiagram where newModelFromId is not null";
        //                 SQLiteDataReader reader = cmd.ExecuteReader();
        //                 while (reader.Read())
        //                 {
        //                     string subFormId = reader["newModelFromId"].ToString();
        //                     foreach (OriginalModelForm form in mainForm.modelFormList)
        //                     {
        //                         if (subFormId.Equals(form.id))
        //                         {
        //                             subFormList.Add(form);
        //                         }
        //                     }
        //                 }
        // 
        //             }
        //             catch (System.Exception ex)
        //             {
        //                 Console.WriteLine(ex.ToString());
        // 
        //             }
        //             finally
        //             {
        //                 this.CloseConnection();
        //             }
        //             return subFormList;
        //         }

        public List<OriginalModelForm> GetNonSubFormList(MainForm mainForm)
        {
            List<OriginalModelForm> nonSubFormList = new List<OriginalModelForm>();

            List<string> subFormIds = this.GetSubFormIds(mainForm);
            //   Console.WriteLine("list all is " + mainForm.modelFormList.Count + " and subFormIds is " + subFormIds.Count);

            foreach (OriginalModelForm form in mainForm.modelFormList)
            {
                bool isSubForm = false;
                foreach (string subFormId in subFormIds)
                {
                    if (subFormId.Equals(form.id))
                    {
                        isSubForm = true;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                if (!isSubForm)
                {
                    nonSubFormList.Add(form);
                }

            }

            return nonSubFormList;
        }



        private List<string> GetSubFormIds(MainForm mainForm)
        {
            List<string> list = new List<string>();
            if (mainForm.modelFormList != null)
            {
                foreach (OriginalModelForm form in mainForm.modelFormList)
                {
                    if (form.diagramList != null)
                    {
                        foreach (OriginalDiagram diagram in form.diagramList)
                        {
                            if (diagram is HighOrderObjectDiagram)
                            {
                                OriginalModelForm childForm = ((HighOrderObjectDiagram)diagram).NewModelForm;
                                if (childForm != null)
                                {
                                    list.Add(childForm.id);
                                }
                            }
                            else if (diagram is HighStateDiagram)
                            {
                                OriginalModelForm childForm = ((HighStateDiagram)diagram).NewModelForm;
                                if (childForm != null)
                                {
                                    list.Add(childForm.id);
                                }
                            }
                            else if (diagram is InformationSourceDiagram)
                            {
                                OriginalModelForm childForm = ((InformationSourceDiagram)diagram).NewModelForm;
                                if (childForm != null)
                                {
                                    list.Add(childForm.id);
                                }

                            }
                        }
                    }
                }
            }


            return list;
        }

        private void AddSubFormForAllDiagrams(MainForm mainForm)
        {
            List<OriginalModelForm> nonSubFormList = this.GetNonSubFormList(mainForm);
            foreach (OriginalModelForm nonSubForm in nonSubFormList)
            {
                this.AddSubFormForForm(nonSubForm,mainForm);
            }
        }

        private void AddSubFormForForm(OriginalModelForm form,MainForm mainForm)
        {
            foreach (OriginalDiagram diagram in form.diagramList)
            {
                this.AddSubFormForDiagram(diagram,mainForm);
            }
        }

        private void AddSubFormForDiagram(OriginalDiagram diagram, MainForm mainForm)
        {
            if (diagram is HighOrderObjectDiagram)
            {
                string newModelFormId = ((HighOrderObjectDiagram)diagram).newModelFormId;
                if (newModelFormId != null && (!"".Equals(newModelFormId)))
                {
                    foreach (OriginalModelForm form in mainForm.modelFormList)
                    {
                        if (newModelFormId.Equals(form.id))
                        {
                            ((HighOrderObjectDiagram)diagram).NewModelForm = (ObjectModelForm)form;
                            this.AddSubFormForForm(form,mainForm);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            else if (diagram is HighStateDiagram)
            {
                string newModelFormId = ((HighStateDiagram)diagram).newModelFormId;
                if (newModelFormId != null && (!"".Equals(newModelFormId)))
                {
                    foreach (OriginalModelForm form in mainForm.modelFormList)
                    {
                        if (newModelFormId.Equals(form.id))
                        {
                            ((HighStateDiagram)diagram).NewModelForm = (StateTransitionModelForm)form;
                            this.AddSubFormForForm(form, mainForm);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
            }
            else if (diagram is InformationSourceDiagram)
            {
                string newModelFormId = ((InformationSourceDiagram)diagram).newModelFormId;
                if (newModelFormId != null && (!"".Equals(newModelFormId)))
                {
                    foreach (OriginalModelForm form in mainForm.modelFormList)
                    {
                        if (newModelFormId.Equals(form.id))
                        {
                            ((InformationSourceDiagram)diagram).NewModelForm = (InformationFlowModelForm)form;
                            this.AddSubFormForForm(form, mainForm);
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }

            }
        }
    }
}
